﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Windows.Forms;
using Shared.Method;
using Shared.Model;
using Client;
using StationTestDll;
using Shared.DJDBDK;
using System.Threading.Tasks;
using System.Text;
using System.Threading;
using Shared.SoftMethod;

namespace ModemWrite
{
    public partial class FormTwo : UserControl
    {
        private string _stationIp = null;

        private string _localIp = null;
        private int _localPort = 0;

        private string _modemIp = null;
        private string _modemUser = null;
        private string _modemPwd = null;

        private int _myFormNum = 0;

        private long _nodeId = 0;
        //private YcdTelnetSecond _telnet = null;
        //private string _ifReset = "0";

        //增加一个事件传递正在写入信息的指令
        public event Action<int> OnWrite;
        public event Action<int> OnFinished;

        //private string _log = "";

        //private List<string> _listLog = new List<string>();
        private string _listLog = string.Empty;

        private object lockLog = new object();

        //所有的产品类型信息
        private List<Device_Type> _listType = null;

        //private int _testNum = 0;
        private int _myVoiceNum = 0;

        //是否自动读取MAC
        private string _autoReadMac = string.Empty;

        private ModemType _modemType = ModemType.DX_926;

        //保存操作的TASK
        //private CancellationTokenSource _tokenTag = null;
        private Thread _testThread = null;

        private int _portOffset = DateTime.Now.Second;

        //private string _portOne = string.Empty;
        //private string _portTwo = string.Empty;
        //获取初始化数据
        public FormTwo(string localIp, int localPort,
            string modemIp, string modemUser, string modemPwd,
            int formNum, List<Device_Type> listType, string stationIp = "127.0.0.1")
        {
            _stationIp = stationIp;

            _localIp = localIp;
            _localPort = localPort;

            _modemIp = modemIp;
            _modemUser = modemUser;
            _modemPwd = modemPwd;

            _myFormNum = formNum;

            _listType = listType;

            //_portOne = portOne;
            //_portTwo = portTwo;

            //_ifReset = ifReset;
            _myVoiceNum = _myFormNum - 1;
            //自动读取MAC
            _autoReadMac = AppSetting.GetValue("AutoReadMac");

            if (string.IsNullOrEmpty(localIp)
                || string.IsNullOrEmpty(modemIp)
                || string.IsNullOrEmpty(modemUser)
                || string.IsNullOrEmpty(modemPwd)
                || localPort <= 1024)
            {
                //初始化的参数不正确
                MessageBox.Show(string.Format("窗口：{0}，初始化参数不正确", _myFormNum));
                this.Dispose();//销毁窗口
            }

            //从APPCONFIG获取配置
            string nodeId = AppSetting.GetValue("StationNodeId");
            if (string.IsNullOrEmpty(nodeId) == false) long.TryParse(nodeId, out _nodeId);

            InitializeComponent();
        }


        private void FormTwo_Load(object sender, EventArgs e)
        {
            if (_autoReadMac == "1") GetMacArp();
        }

        //通过ARP获取MAC地址
        private void GetMacArp()
        {
            Task.Factory.StartNew(() =>
            {
                SetTextBoxReadOnly(true);

                while (PingBaseClass.PingTest(_localIp, _modemIp) == true) Thread.Sleep(2000);

                //PING光猫
                int pingOkTimes = 0;
                while (true)
                {
                    if (PingBaseClass.PingTest(_localIp, _modemIp))
                    {
                        pingOkTimes++;
                        if (pingOkTimes >= 4)
                            break;
                    }
                    else
                    {
                        pingOkTimes = 0;
                    }
                    Thread.Sleep(500);
                }

                string mac = string.Empty;

                while (
                string.IsNullOrEmpty(mac = ArpBaseClass.GetMacFromIp(_localIp, _modemIp))
                )
                {
                    Thread.Sleep(3000);
                }

                SetControlText(this.textBoxMacAddr, mac, Color.Black);

                CheckMessage();
            });

        }

        //输入MAC
        private void textBoxMacAddr_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (this.textBoxMacAddr.ReadOnly) return;
            //只能输入16进制数字和回车符号'\r'或者'\n'，MAC地址中的字符只能位0-9,A~F
            if (e.KeyChar == '\n' || e.KeyChar == '\r')
            {
                e.Handled = true;
                if (this.textBoxMacAddr.Text.Trim().Length != 12)
                {
                    AppendRichTextBox("MAC地址不为12位数");
                    this.textBoxMacAddr.Clear();
                    this.textBoxMacAddr.Focus();
                }
                else
                {
                    this.textBoxMacAddr.ReadOnly = true;

                    _testThread = new Thread(new ThreadStart(() =>
                    {
                        CheckMessage();
                    }));

                    _testThread.Start();
                }
            }
            else if ((e.KeyChar >= 'a' && e.KeyChar <= 'f')
                || (e.KeyChar >= 'A' && e.KeyChar <= 'F')
                || (e.KeyChar >= '0' && e.KeyChar <= '9')
                || (e.KeyChar == 8))
            {
                //判断是否位16进制字符，将小写全部转为大写
                e.Handled = false;
            }
            else
            {
                MessageBox.Show("只能输入数字和A-F");
                e.Handled = true;
            }
        }

        private void CheckMessage()
        {
            //SetTextBoxEnable(false);
            ClearText(this.richTextBoxMsg);

            string mac = this.textBoxMacAddr.Text.Trim();

            _listLog = string.Empty;

            OnWrite?.Invoke(_myFormNum);//发送正在写入信息的指令
            AppendRichTextBox(string.Format("本产品在【{0}】号窗口测试", _myFormNum));

            //判断此MAC地址是否已经存在了
            if (PublicData.ListAddress.ContainsKey(mac))
            {
                AppendRichTextBox("此MAC地址正在其他窗口使用，请勿重复扫描");
                //SetTextBoxReadOnly(false);
                //MacFocus();

                FinallyDone();
                return;
            }
            else
            {
                PublicData.ListAddress.Add(mac, _myFormNum);
            }

            //到数据库中查找是否存在相应的MAC
            Device_Data deviceW = new Device_Data();
            deviceW.SetWhere();
            deviceW.MACAddr = mac;
            deviceW.USED = true;

            var selectDevice = MethodWcf.SelectDeviceDataClient(deviceW);
            if (selectDevice.result == false)
            {
                AppendRichTextBox("MAC地址未分配，或MAC未上传不能使用");

                SetResultOne("请分配MAC", false);

                //删除相关的MAC信息
                FinallyDone(mac);
                return;
            }

            //获取产品型号的相关数据
            var deviceType = GetDeviceType(selectDevice.value[0].DeviceType, selectDevice.value[0].HW_PROVINCE_NAME);

            if (deviceType == null)
            {
                AppendRichTextBox("未能获取产品的类型信息");

                SetResultOne("未能获得类型信息，请检查DeviceType", false);

                FinallyDone(mac);
                return;
            }

            //显示正在测试当中
            //SetTestState(true, "WAITFOR");
            SetControlText(this.labelTestResult, "WAITFOR", Color.Black);

            //PING光猫
            int pingOkTimes = 0;
            for (int i = 0; i < 80; i++)
            {
                if (PingBaseClass.PingTest(_localIp, _modemIp))
                {
                    pingOkTimes++;
                    if (pingOkTimes >= 4)
                        break;
                }
                else
                {
                    pingOkTimes = 0;
                }
                Thread.Sleep(500);
            }

            if (pingOkTimes < 4)
            {
                AppendRichTextBox("未能成功PING通光猫");
                FinallyDone(mac);
                return;
            }

            //尝试5次1秒一次
            //SetTestState(false, "TESTING");
            SetControlText(this.labelTestResult, "TESTING", Color.Black);

            ////初始化telnet
            YcdTelnetSecond tel = null;
            for (int i = 0; i < 5; i++)
            {
                ////初始化telnet
                //tel = TelnetModem();
                if (_portOffset >= 800) _portOffset = 0;
                _portOffset++;

                tel = YcdTelnetMethod.TelnetModem(_localIp, _modemIp, _localPort + _portOffset, 23, _modemUser, _modemPwd);


                if (tel == null)
                {
                    AppendRichTextBox("TELNET光猫失败");
                }
                else
                {
                    break;
                }

                Thread.Sleep(5000);
            }

            if (tel == null)
            {
                //判断是否经过了此工序，如果经过了则直接显示PASS

                //判断是否需要进行此工序
                bool hasChecked = ProductCheck(mac);

                if (hasChecked)
                {
                    AppendRichTextBox("此产品已经通过了信息检查，无需再次检查");

                    //删除相关的MAC信息
                    FinallyDone(mac, true);
                    return;
                }

                FinallyDone(mac);
                return;
            }


            //获取光猫上的MAC地址，并绑定MAC与YCDMAC
            string ycdMac = MacClass.GetModemMacAddress(tel);

            #region 新判断逻辑，使用两个product

            /*新的判断逻辑，查询ycdMac对应的pro_ycd和mac对应的pro_mac
             * 1、判断ycdMac与mac是否一致，一致的话，查询一次后可以直接写入信息->second
             * 2、判断pro_mac的站位与当前站位是否一致，不一致的话，此MAC多半重号->forth
             * 3、无pro_ycd的话，不能进行下一步->first
             * 4、只有pro_ycd的话，可以直接进行下一步，写入信息->third
             * 5、有pro_ycd和pro_mac，判断ycdMac与MAC->fifth
             * 6、两个PRODUCT中的判断逻辑
             * ①ycdMac同，MAC同；（直接写入信息）
             * ②ycdMac同，MAC不同；（不存在）
             * ③ycdMac不同，MAC同；(重号的，解绑当前的MAC，要求贴新的MAC）
             * ④ycdMac不同，MAC不同；（解绑原来的MAC，绑定新的主板）
             * */

            PRODUCT productW = new PRODUCT();
            //查ycd对应的proYcd
            productW.SetWhere();
            if (ycdMac.ToUpper().StartsWith(SharedData.YCD_MAC_EPON_START) == false && ycdMac.ToUpper().StartsWith(SharedData.YCD_MAC_GPON_START) == false)
                productW.MAC = ycdMac;
            else
                productW.YCD_MAC = ycdMac;

            var selectYcdPro = MethodWcf.SelectProductClient(productW);
            if (selectYcdPro.result == false)//ycdMAC对应的product不存在
            {
                AppendRichTextBox(string.Format("查询MAC[{0}]对应的产品信息失败，请将光猫拿到信息写入重写", ycdMac));
                FinallyDone(mac);
                return;
            }

            if (selectYcdPro.value.Count != 1)
            {
                //解绑
                for (int i = 0; i < selectYcdPro.value.Count; i++)
                {
                    var product = selectYcdPro.value[i];
                    if (_nodeId == product.NODE_ID)
                    {
                        product.Clear();
                        product.SetWhere();
                        product.YCD_MAC = product.YCD_MAC;
                        product.SetUpdate();
                        product.MAC = null;

                        MethodWcf.UpdateProductClient(product);
                    }
                }

                AppendRichTextBox(string.Format("MAC[{0}]对应的产品信息为[{1}]条，请重新扫描，并联系管理员", ycdMac, selectYcdPro.value.Count));
                FinallyDone(mac);
                return;
            }

            if (ycdMac.ToUpper() == mac.ToUpper())//内外MAC一致
            {
                ycdMac = selectYcdPro.value[0].YCD_MAC;
                AppendRichTextBox("内外MAC一致，可以写数据到光猫");
                goto OUT;
            }

            productW.Clear();
            productW.SetWhere();
            productW.MAC = mac;
            var selectMacPro = MethodWcf.SelectProductClient(productW);

            if (selectMacPro.result == false)//没有pro_mac
            {
                ycdMac = selectYcdPro.value[0].YCD_MAC;
                AppendRichTextBox("查询MAC，没有找到相关信息，可以写数据到光猫");
                goto OUT;
            }

            //MAC地址不唯一
            if (selectMacPro.value.Count != 1)
            {
                //解绑
                for (int i = 0; i < selectMacPro.value.Count; i++)
                {
                    var product = selectMacPro.value[i];
                    if (_nodeId == product.NODE_ID)
                    {
                        product.Clear();
                        product.SetWhere();
                        product.YCD_MAC = product.YCD_MAC;
                        product.SetUpdate();
                        product.MAC = null;

                        MethodWcf.UpdateProductClient(product);
                    }
                }

                AppendRichTextBox(string.Format("MAC[{0}]对应的产品信息为[{1}]条，请重新扫描，并联系管理员", mac, selectMacPro.value.Count));
                FinallyDone(mac);
                return;
            }

            if (selectMacPro.value[0].NODE_ID != _nodeId)//站位与当前站位不一致，原因是重号
            {
                AppendRichTextBox(string.Format("请贴新码，MAC[{0}]的站位ID[{1}]与信息检查的站位ID不一致", mac, selectMacPro.value[0].NODE_ID, _nodeId));
                FinallyDone(mac);
                return;
            }

            //提取两者的YCDMAC与MAC
            string ycdMac1 = selectYcdPro.value[0].YCD_MAC;
            string mac1 = selectYcdPro.value[0].MAC;
            string ycdMac2 = selectMacPro.value[0].YCD_MAC;
            string mac2 = selectMacPro.value[0].MAC;

            if (ycdMac1 == ycdMac2 && mac1 == mac2)
            {
                ycdMac = ycdMac1;
                AppendRichTextBox("内外MAC已经绑定，可以写产品信息");
            }
            else if (ycdMac1 == ycdMac2 && mac1 != mac2)//数据库会拦截下来，以防万一留下来
            {
                AppendRichTextBox(string.Format("内部MAC[{0}]地址重复，请联系管理员", ycdMac1));
                FinallyDone(mac);
                return;
            }
            else if (ycdMac1 != ycdMac2 && mac1 == mac2)//这个会在判断product数量的地方拦截下来，以防万一留下来
            {
                AppendRichTextBox(string.Format("已经有一个内部MAC为[{1}]的光猫绑定了MAC[{0}]，请贴新MAC地址", mac2, ycdMac2));

                FinallyDone(mac);
                return;
            }
            else if (ycdMac1 != ycdMac2 && mac1 != mac2
                && selectMacPro.value[0].END_TIME <= (DateTime.Now.Hour >= 8 ? DateTime.Now.AddHours(-6) : DateTime.Now.AddHours(-18)))
            {
                //解绑ycdMac2与mac2之间的绑定关系，4小时内未处理的不良品将解绑MAC，用于回收的MAC地址
                productW.Clear();
                productW.SetWhere();
                productW.YCD_MAC = ycdMac2;
                productW.SetUpdate();
                productW.MAC = null;
                MethodWcf.UpdateProductClient(productW);

                ycdMac = ycdMac1;

                AppendRichTextBox("内外MAC绑定的信息不一致，解绑外部MAC，绑定内外MAC，可以写光猫信息");
            }
            else
            {
                AppendRichTextBox("请贴新MAC后，再次测试");
                FinallyDone(mac);
                return;
            }

            OUT://跳转到此处
            #endregion

            #region 判断逻辑OLD

            ////如果MAC地址不是内部的MAC，则在数据库中找到对应的MAC地址
            //if (ycdMac.ToUpper().StartsWith(SharedData.YCD_MAC_EPON_START) == false && ycdMac.ToUpper().StartsWith(SharedData.YCD_MAC_GPON_START) == false)
            //{
            //    PRODUCT proW = new PRODUCT();
            //    //查询MAC是否解绑，若没有解绑，YCDMAC必须与MAC一致才可以绑定
            //    proW.SetWhere();
            //    proW.MAC = mac;
            //    var selectProCount = MethodWcf.SelectProductCountClient(proW);
            //    if (selectProCount.result && selectProCount.message != "0" && mac != ycdMac)
            //    {
            //        AppendRichTextBox("此外部MAC已经绑定过其他的内部MAC，此外部MAC地址可能重号");
            //        FinallyDone(mac);
            //        return;
            //    }

            //    //找到此MAC绑定的内部MAC地址
            //    //selectPro = null;//重置为空
            //    proW.Clear();
            //    proW.SetWhere();
            //    proW.MAC = ycdMac;
            //    var selectPro = MethodWcf.SelectProductClient(proW);
            //    if (selectPro.result == false)
            //    {
            //        AppendRichTextBox("此外部MAC地址未绑定内部MAC，请拿到信息写入工位重新写入");
            //        FinallyDone(mac);
            //        return;
            //    }

            //    ycdMac = selectPro.value[0].YCD_MAC;//修改YCDMAC为绑定前的MAC地址
            //}

            #endregion

            //查询YCD_DEVICE，并更新Device的LightModuleSn
            YCD_DEVICE ycdW = new YCD_DEVICE();
            ycdW.SetWhere();
            ycdW.YCD_MAC = ycdMac;

            var selectYcd = MethodWcf.SelectYcdDeviceClient(ycdW);
            if (selectYcd.result == false)
            {
                AppendRichTextBox("查询YCD_MAC失败");
                FinallyDone(mac);
                return;
            }
#if true
            //判断YCDMAC与MAC的BOSA类型是否一致
            if (selectYcd.value[0].PON_TYPE != selectDevice.value[0].PONType)
            {
                AppendRichTextBox("内部MAC与外部MAC的BOSA类型不一致");
                FinallyDone(mac);
                return;
            }
#endif

            AppendRichTextBox("判断是否可以进行信息检查的工作");

            string msg = "";

            //判断是否可以开始信息检查的工作
            bool canTest = StationTest.IfCanTest(ycdMac, ref msg, _stationIp);

            //WriteLog(msg);
            AppendRichTextBox(msg);

            if (canTest == false)
            {
                //删除相关的MAC信息
                FinallyDone(mac);
                tel.Close();
                return;
            }

            bool wifiMsgCheck = SoftShared.CheckWifiMsg(tel, out msg);

            AppendRichTextBox(msg);

            if (wifiMsgCheck == false)
            {
                FinallyDone(mac);
                tel.Close();
                return;
            }

            //开启灯光
            TelnetSendAndRecv(tel, "mpctl led on", "#");

            //给device赋值
            if (string.IsNullOrEmpty(selectYcd.value[0].LIGHT_MODULE_SN) == false)
                selectDevice.value[0].LightModuleSN = selectYcd.value[0].LIGHT_MODULE_SN;

            //写真实的Device信息
            var checkMsg = ModemMsgCheck(selectDevice.value[0], deviceType, ycdMac, tel);

            bool voiceTest = false;
            if (checkMsg)
            {
                voiceTest = VoiceButtonTest(tel, selectDevice.value[0]);
            }

            //System.Threading.Thread.Sleep(1000);
            AppendRichTextBox("信息检查语言测试工作完成");

            if (checkMsg && voiceTest)
            {
                bool updateDevice = false, updateProduct = false;

                //更新BOSA_SN
                if (string.IsNullOrEmpty(selectYcd.value[0].LIGHT_MODULE_SN) == false)
                {
                    deviceW.SetUpdate();
                    deviceW.LightModuleSN = selectYcd.value[0].LIGHT_MODULE_SN;
                    updateDevice = MethodWcf.UpdateDeviceDataClient(deviceW).result;
                }
                else updateDevice = true;

                //绑定MAC与ycdMAC
                PRODUCT proU = new PRODUCT();
                proU.SetWhere();
                proU.YCD_MAC = ycdMac;
                proU.SetUpdate();
                proU.MAC = mac;
                //proU.PROCESS_ALL = selectDevice.value[0].ORDER_SN;//Save Order SN
                updateProduct = MethodWcf.UpdateProductClient(proU).result;

                AppendRichTextBox(string.Format("更新BOSA结果为：{0}，绑定MAC结果为：{1}", updateDevice, updateProduct));

                //写真实的MAC地址
                bool writeMac = false;
                if (updateProduct && updateDevice)
                {
                    writeMac = TelnetSendAndRecv(tel, string.Format("flash set ELAN_MAC_ADDR {0}", mac), "=" + mac);
                }

                //将写日志放到最后面
                if (updateDevice && updateProduct && writeMac)
                {
                    AppendRichTextBox("等待恢复出厂设置完成……");

                    //ResetModem(tel, deviceType.DeviceType);
                    bool resetResult = SoftShared.ResetModem(tel, _modemType, out msg);
                    AppendRichTextBox(msg);

                    bool writeLogResult = StationTest.SaveTestData(ycdMac, resetResult, GetListLog(), ref msg, _stationIp);

                    tel.Send("exit");
                    tel.Close();

                    Thread.Sleep(6000);
                    FinallyDone(mac, resetResult && writeLogResult);

                    return;//正常返回
                }

            }
            //将省份信息回写到光猫中
            TelnetSendAndRecv(tel, "flash set HW_PROVINCE_NAME FACTORY", "=FACTORY");

            //写LOG信息
            var writeRet = StationTest.SaveTestData(ycdMac, false, GetListLog(), ref msg, _stationIp);
            AppendRichTextBox(string.Format("写LOG信息结果为：{0}，返回信息为：{1}", writeRet, msg));

            //关闭socket
            tel.Send("exit");
            tel.Close();
            FinallyDone(mac);
        }



        private bool VoiceButtonTest(YcdTelnetSecond tel, Device_Data device)
        {
#if false
            //USB测试
            bool usbTestResult = SoftShared.UsbTest(tel, this.richTextBoxMsg, this);

            if (usbTestResult == false)
            {
                SoftShared.AppendText(this, this.richTextBoxMsg, "USB测试失败");
                return false;
            }
            else
            {
                SoftShared.SetControl(this, this.labelTestResult, "USB测试成功", Color.BlueViolet);
            }


            //语言测试
            string keyVoice = "chid 0 init";

            //语音测试
            bool voiceTestResult = VoiceTest(_myVoiceNum, tel, keyVoice);


            if (voiceTestResult == false)
            {
                AppendRichTextBox("语音测试失败");

                return false;
            }
            else
            {
                SetControlText(this.labelTestResult, "语音测试成功", Color.BlueViolet);
            }

            //开启灯光
            bool ret = tel.SendAndRecv("mpctl led on", "#", out string msg);
            SoftShared.AppendText(this, this.richTextBoxMsg, msg + "\r开启灯光指令已经完成");

            string keywifi = string.Empty;
            string keyreset = string.Empty;
            string keywps = string.Empty;

            string outMsg;
            if (_modemType == ModemType.YD_9603C)//移动
            {
                TelnetSendAndRecv(tel, "killall -9 lanNetInfo", "#");

                ret = tel.SendAndRecv("cat /proc/kmsg & led test start", "#", out outMsg);
                SoftShared.AppendText(this, this.richTextBoxMsg, outMsg);

                keywifi = "wifi button";
                keyreset = "reset button";
                keywps = "wps button";
            }
            else if (_modemType == ModemType.LT_9603C)//联通
            {
                ret = tel.SendAndRecv("cat /proc/kmsg & led test start", "#", out outMsg);
                SoftShared.AppendText(this, this.richTextBoxMsg, outMsg);

                keywifi = "wifi button";
                keyreset = "reset button";
                keywps = "led button";
            }
            else if (_modemType == ModemType.DX_9603C)//电信9603C
            {
                ret = tel.SendAndRecv("cat /proc/kmsg &\r\n", "#", out outMsg);
                SoftShared.AppendText(this, this.richTextBoxMsg, outMsg);

                keywifi = "wifi button";
                keyreset = "reset button";
            }
            else if ( _modemType == ModemType.DX_9603C_ITV)//电信9603C ITV
            {
                ret = tel.SendAndRecv("cat /proc/kmsg & led test start\r\n", "#", out outMsg);
                SoftShared.AppendText(this, this.richTextBoxMsg, outMsg);

                keywifi = "wifi button";
                keyreset = "led button";
            }
            else if (_modemType == ModemType.DX_9603)
            {
                ret = tel.SendAndRecv("cat /proc/kmsg & led test start", "#", out outMsg);
                SoftShared.AppendText(this, this.richTextBoxMsg, outMsg);

                keywifi = "<4>wifi";
                keyreset = "do nothing";
            }

            if (ret == false)
            {
                SoftShared.AppendText(this, this.richTextBoxMsg, "未能开启按键测试功能");
                return false;
            }

            //

            bool buttonTestResult = SoftShared.ButtonTest(tel, this, this.richTextBoxMsg, this.labelTestResult, keywifi, keyreset, keywps);


            if (buttonTestResult == false)
            {
                SoftShared.AppendText(this, this.richTextBoxMsg, "按键测试失败");
                return false;
            }
            else
            {
                SoftShared.SetControl(this, this.labelTestResult, "按键测试成功", Color.BlueViolet);
            }

            return true;
#endif

#if true

            //USB测试
            bool usbTestResult = UsbTest(tel);
            if (usbTestResult == false)
            {
                AppendRichTextBox("USB测试失败");

                return false;
            }
            else
            {
                SetControlText(this.labelTestResult, "USB测试成功", Color.BlueViolet);
            }

            //语言测试
            string keyVoice = "chid 0 init";


            //语音测试
            bool voiceTestResult = VoiceTest(_myVoiceNum, tel, keyVoice);


            if (voiceTestResult == false)
            {
                AppendRichTextBox("语音测试失败");

                return false;
            }
            else
            {
                SetControlText(this.labelTestResult, "语音测试成功", Color.BlueViolet);
            }

            string keywifi = string.Empty, keyreset = string.Empty,keyled=string.Empty;
            bool ret = false;

            if (_modemType == ModemType.YD_924)//移动
            {
                TelnetSendAndRecv(tel, "killall -9 lanNetInfo", "#");

                ret = TelnetSendAndRecv(tel, "cat /proc/kmsg & led test start", "#");
                keywifi = "wifi button";
                keyreset = "reset button";
            }
            else if (_modemType == ModemType.LT_952)//联通
            {
                ret = TelnetSendAndRecv(tel, "cat /proc/kmsg & led test start", "#");
                keywifi = "wifi button";
                keyreset = "reset button";
            }
            else if (_modemType == ModemType.DX_926)//电信9603C
            {
                ret = TelnetSendAndRecv(tel, "cat /proc/kmsg &\r\n", "#");
                keywifi = "wifi button";
                keyreset = "reset button";
            }
            else if (_modemType == ModemType.DX_927)//电信9603C
            {
                ret = TelnetSendAndRecv(tel, "cat /proc/kmsg &\r\n", "#");
                //keywifi = null;
                keyreset = "reset button";
            }
            else if (_modemType == ModemType.DX_101)//电信9603C ITV
            {
                ret = TelnetSendAndRecv(tel, "cat /proc/kmsg & led test start\r\n", "#");

                keywifi = "wifi button";
                keyled = "led button";
                keyreset = "reset button";
            }
            else if (_modemType == ModemType.DX_924)
            {
                ret = TelnetSendAndRecv(tel, "cat /proc/kmsg & led test start", "#");
                keywifi = "<4>wifi";
                keyreset = "do nothing";
            }

            //确认灯光正常
            if (ret == false)
            {
                AppendRichTextBox("未能开启按键测试功能");
                return false;
            }

            bool buttonTestResult = ButtonTest(tel, keywifi, keyreset,keyled);

            if (buttonTestResult == false)
            {
                AppendRichTextBox("按键测试失败");
                return false;
            }
            else
            {
                SetControlText(this.labelTestResult, "按键测试成功", Color.BlueViolet);
            }

            return true;
#endif
        }

        //语音测试，返回true or false
        private bool VoiceTest(int voiceNum, YcdTelnetSecond tel, string keyWord = "MPtest")
        {
            //判断参数是否正确
            if (voiceNum > 7 || voiceNum < 0 || tel == null || tel.Connected == false)
            {
                AppendRichTextBox("语音测试失败，传入参数错误");
                return false;
            }
            //挂机
            VoiceBaseClass.ResetChannel(voiceNum);

            //bool recvResult = TelnetSendAndRecv(tel, "voipmp", keyWord);//18.1.25修改，兼容R方案1.23日版本
            string outMsg;
            bool recvResult = tel.SendAndRecv("voipmp", keyWord, out outMsg, 5000);

            AppendRichTextBox(outMsg);
            if (outMsg.Contains("getHookState"))
            {
                AppendRichTextBox("语音回显异常，不能测试语音功能");
                return false;
            }

            if (tel.SendAndRecv(string.Empty, "getHookState", out outMsg, 2000))
            {
                AppendRichTextBox(outMsg + "\r\n语音回显异常，不能测试语音功能");
                return false;
            }

            if (recvResult == false)
            {
                AppendRichTextBox("未能开启语音测试功能");
                return false;
            }
            else
                AppendRichTextBox("开启语音测试");


            //开始测试语音
            recvResult = VoiceBaseClass.DialNum(voiceNum, "*159#", out string msg);

            AppendRichTextBox(msg);

            //tel.GetReturnMsg("#", out msg);
            bool exitResult = tel.SendAndRecv(null, "#", out msg);

            tel.Send(new byte[] { 0x03 });//end voice test

            AppendRichTextBox(msg);

            return recvResult&&exitResult;
        }

        //USB测试
        private bool UsbTest(YcdTelnetSecond tel)
        {
            //判断tel是否连接着
            if (tel == null || tel.Connected == false)
            {
                AppendRichTextBox("USB测试失败，传入参数错误");
                return false;
            }

            bool ret = false;

            //Thread.Sleep(500);

            //重试30次
            for (int i = 0; i < 30; i++)
            {
                ret = TelnetSendAndRecv(tel, "usbmp", "success");

                if (ret) break;

                //Thread.Sleep(500);
            }

            if (ret) AppendRichTextBox("USB测试成功");
            else
            {
                AppendRichTextBox("USB测试失败");
                return false;
            }

            return true;
        }

        //按键测试
        private bool ButtonTest(YcdTelnetSecond tel, string keywifi, string keyreset,string keyled)
        {
            if (ButtonTesting(tel, keyreset, "按复位按钮") == false) return false;

            if (string.IsNullOrEmpty(keywifi) == false && ButtonTesting(tel, keywifi, "按WIFI按钮") == false) return false;

            if (string.IsNullOrEmpty(keyled) == false && ButtonTesting(tel, keyled, "按LED按钮") == false) return false;

            return true;

#if false
            //判断tel是否连接着
            if (tel == null || tel.Connected == false)
            {
                AppendRichTextBox("按键测试失败，传入参数错误");
                return false;
            }

            bool ret = false;

            //WIFI按钮
            //SetTestState(true, "灯亮，按WIFI按钮");
            SetControlText(this.labelTestResult, "按WIFI按钮", Color.BlueViolet);

            //重试30次
            for (int i = 0; i < 30; i++)
            {
                string msg;
                //ret = tel.GetReturnMsg(keywifi, out msg);
                ret = tel.SendAndRecv(null, keywifi, out msg, 1800);

                AppendRichTextBox(msg);

                if (ret) break;

                //Thread.Sleep(500);
            }

            if (ret) AppendRichTextBox("WIFI按钮测试成功");
            else
            {
                AppendRichTextBox("WIFI按钮测试失败");
                return false;
            }

            //复位按钮
            //SetTestState(true, "按复位按钮");
            SetControlText(this.labelTestResult, "按复位按钮", Color.BlueViolet);
            //重试30次
            for (int i = 0; i < 30; i++)
            {
                string msg;
                //ret = tel.GetReturnMsg(keyreset, out msg);
                ret = tel.SendAndRecv(null, keyreset, out msg, 1800);
                AppendRichTextBox(msg);

                if (ret) break;

                //Thread.Sleep(500);
            }

            if (ret) AppendRichTextBox("复位按钮测试成功");
            else
            {
                AppendRichTextBox("复位按钮测试失败");
                return false;
            }

            return true;
#endif
        }

        private bool ButtonTesting(YcdTelnetSecond tel, string key, string tips)
        {
            //判断tel是否连接着
            if (tel == null || tel.Connected == false)
            {
                AppendRichTextBox("按键测试失败，传入参数错误");
                return false;
            }

            bool ret = false;

            SetControlText(labelTestResult, tips, Color.BlueViolet);

            //重试30次
            for (int i = 0; i < 30; i++)
            {
                ret = tel.SendAndRecv(null, key, out string msg, 1800);

                AppendRichTextBox(msg);

                if (ret) break;
            }

            if (ret) AppendRichTextBox("测试成功");
            else AppendRichTextBox("测试失败");

            return ret;
        }

        private bool ProductCheck(string mac)
        {
            //查找过程表，看有没有一条已经通过的数据
            PRODUCT productW = new PRODUCT();
            productW.SetWhere();

            productW.MAC = mac;
            productW.TEST_RESULT = "Y";
            productW.NODE_ID = _nodeId;
            productW.NODE_STATE = true;//表示工序完成

            var selectProduct = MethodWcf.SelectProductCountClient(productW);

            if (selectProduct.result && selectProduct.message == "1") return true;
            return false;
        }


        private bool ModemMsgCheck(Device_Data deviceData, Device_Type deviceType, string ycdMac, YcdTelnetSecond tel)
        {

            //判断是MTK还是R方案
            //R方案的EPON和GPON
            bool checkResult = WriteDeviceR(deviceData, deviceType, tel);

            return checkResult;
        }

        private bool WriteDeviceR(Device_Data deviceData, Device_Type deviceType, YcdTelnetSecond tel)
        {
            //判断网口速度是否正常
            string msg;
            bool speed = YcdTelnetMethod.CheckPortSpeed(tel,out msg);

            AppendRichTextBox(msg);
            //AppendRichTextBox(msg2);

            if (speed == false)
            {
                SetResultOne("网口速度不正常", false);
                return false;
            }
            else
            {
                SetResultOne("网口速度正常", true);
            }

            //固件版本检查
            var writeResult = tel.SendAndRecv("cat /etc/swver", deviceType.BuildTime, out msg);
            if (writeResult == false) { SetResultOne("校验编译时间失败", false); return false; }
            else { SetResultOne("校验编译时间成功", true); }

            //获取固件版本
            if (msg.Contains("CMCC") && deviceData.DeviceType.Contains("CMCC"))//移动
            {
                _modemType = ModemType.YD_924;
            }
            else if (msg.Contains("_CU") && deviceData.DeviceType.Contains("952"))//联通
            {
                _modemType = ModemType.LT_952;
            }
            else if (msg.Contains("Yueme") && msg.Contains("RTL9607C"))
            {
                _modemType = ModemType.DX_927;
            }
            else if (msg.Contains("Yueme") && msg.Contains("9603C")&&msg.Contains("926") )//电信9603C
            {
                _modemType = ModemType.DX_926;
            }
            else if (msg.Contains("Yueme") && msg.Contains("9603C") &&deviceData.DeviceType.Contains("521"))//电信融合网关
            {
                _modemType = ModemType.DX_101;
            }
            else if (deviceData.DeviceType.Contains("924"))
            {
                _modemType = ModemType.DX_924;
            }
            else
            {
                //AppendRichTextBox("移动联通电信FLASH混料\r固件版本与MAC地址对应的产品品牌不一致\r");
                //SoftShared.SetControl(this, this.labelTestResult, "FLASH混料", Color.Red);
                //return false;
                _modemType = ModemType.DX_926;
            }

            //设备序列号
            //writeResult = WriteAndReadMsg(tel, string.Format("flash set HW_SERIAL_NO {0}", deviceData.OUI2), "flash get HW_SERIAL_NO", "=" + deviceData.OUI2, "=" + deviceData.OUI2);
            writeResult = TelnetSendAndRecv(tel, string.Format("flash set HW_SERIAL_NO {0}", deviceData.OUI2), "=" + deviceData.OUI2);
            if (writeResult == false) { SetResultOne("写设备序列号失败", false); return false; }
            else { SetResultOne("写设备序列号成功", true); }

            //设备型号
            //ADD_18.3.20，兼容新的类型
            string type = deviceData.DeviceType.Replace(" ", "");
            if (type.Contains("_"))
            {
                type = type.Substring(0, type.IndexOf("_"));
            }
            //deviceData.DeviceType = deviceData.DeviceType.Substring(0, deviceData.DeviceType.Length - deviceData.DeviceType.IndexOf("_"));

            //writeResult = WriteAndReadMsg(tel, string.Format("flash set HW_CWMP_PRODUCTCLASS {0}",type), "flash get HW_CWMP_PRODUCTCLASS", "=" + type, "=" + type);
            writeResult = TelnetSendAndRecv(tel, string.Format("flash set HW_CWMP_PRODUCTCLASS {0}", type), "=" + type);
            if (writeResult == false) { SetResultOne("写设备型号失败", false); return false; }
            else { SetResultOne("写设备型号成功", true); }

            if(_modemType== ModemType.LT_952 && deviceData.DeviceType.Contains("PT952G"))
            {
                writeResult = tel.SendAndRecv("flash set PON_VENDOR_ID YHTC", "=YHTC", out msg);
                if (writeResult == false) { SetResultOne("写入PON_VENDOR_ID失败", false); return false; }
                else { SetResultOne("写入PON_VENDOR_ID成功", true); }

                writeResult = tel.SendAndRecv("flash set GPON_ONU_MODEL PT952G", "=PT952G", out msg);
                if (writeResult == false) { SetResultOne("写入GPON_ONU_MODEL失败", false); return false; }
                else { SetResultOne("写入GPON_ONU_MODEL成功", true); }
            }

            //XPON型号
            string ponMode = null;
            if (deviceData.PONType == "STIA")
            {
                ponMode = "1";
                //写BOB信息
                //tel.Send("prolinecmd bobinfo UX GPON write 1 &\r\n");
            }
            else
            {
                ponMode = "2";
                //写BOB初始化信息
                //tel.Send("prolinecmd bobinfo UX EPON write 1 &\r\n");
            }

            //writeResult = WriteAndReadMsg(tel, string.Format("flash set PON_MODE {0}", ponMode), "flash get PON_MODE", "=" + ponMode, "=" + ponMode);
            writeResult = TelnetSendAndRecv(tel, string.Format("flash set PON_MODE {0}", ponMode), "=" + ponMode);
            if (writeResult == false) { SetResultOne("写PON的型号失败", false); return false; }
            else { SetResultOne("写PON的型号成功", true); }

            //硬件版本
            //writeResult = WriteAndReadMsg(tel, string.Format("flash set HW_HWVER {0}", deviceType.HWVersion), "flash get HW_HWVER", "=" + deviceType.HWVersion, "=" + deviceType.HWVersion);
            writeResult = TelnetSendAndRecv(tel, string.Format("flash set HW_HWVER {0}", deviceType.HWVersion), "=" + deviceType.HWVersion);
            if (writeResult == false) { SetResultOne("写设备硬件版本失败", false); return false; }
            else { SetResultOne("写设备硬件版本成功", true); }

            //普通用户密码
            //writeResult = WriteAndReadMsg(tel, string.Format("flash set DEFAULT_USER_PASSWORD {0}", deviceData.WedPassword), "flash get DEFAULT_USER_PASSWORD", "=" + deviceData.WedPassword, "=" + deviceData.WedPassword);
            writeResult = TelnetSendAndRecv(tel, string.Format("flash set DEFAULT_USER_PASSWORD {0}", deviceData.WedPassword), "=" + deviceData.WedPassword);
            if (writeResult == false) { SetResultOne("写普通用户密码失败", false); return false; }
            else { SetResultOne("写普通用户密码成功", true); }

            //无线名称
            //writeResult = WriteAndReadMsg(tel, string.Format("flash set DEFAULT_WLAN_SSID {0}", deviceData.WIFI_SSID), "flash get DEFAULT_WLAN_SSID", "=" + deviceData.WIFI_SSID, "=" + deviceData.WIFI_SSID);
            writeResult = TelnetSendAndRecv(tel, string.Format("flash set DEFAULT_WLAN_SSID {0}", deviceData.WIFI_SSID), "=" + deviceData.WIFI_SSID);
            if (writeResult == false) { SetResultOne("写WIFI名称失败", false); return false; }
            else { SetResultOne("写WIFI名称成功", true); }

            //无线密钥
            //writeResult = WriteAndReadMsg(tel, string.Format("flash set DEFAULT_WLAN_WPAKEY {0}", deviceData.WIFI_Password), "flash get DEFAULT_WLAN_WPAKEY", "=" + deviceData.WIFI_Password, "=" + deviceData.WIFI_Password);
            writeResult = TelnetSendAndRecv(tel, string.Format("flash set DEFAULT_WLAN_WPAKEY {0}", deviceData.WIFI_Password), "=" + deviceData.WIFI_Password);
            if (writeResult == false) { SetResultOne("写WIFI密码失败", false); return false; }
            else { SetResultOne("写WIFI密码成功", true); }

            //非联通写，itv_ssid不为空要写
            if (string.IsNullOrEmpty(deviceData.ITV_SSID) == false)
            {
                //ITV名称
                writeResult = TelnetSendAndRecv(tel, string.Format("flash set HW_SSID2ND {0}", deviceData.ITV_SSID), "=" + deviceData.ITV_SSID);
                if (writeResult == false) { SetResultOne("写ITV SSID名称失败", false); return false; }
                else { SetResultOne("写ITV SSID成功", true); }

                //ITV密钥
                writeResult = TelnetSendAndRecv(tel, string.Format("flash set HW_WPAKEY2ND {0}", deviceData.ITV_Password), "=" + deviceData.ITV_Password);
                if (writeResult == false) { SetResultOne("写ITV 密码失败", false); return false; }
                else { SetResultOne("写ITV 密码成功", true); }
            }

            //光模块序列号
            //writeResult = WriteAndReadMsg(tel, string.Format("flash set HW_LIGHT_SN {0}", deviceData.LightModuleSN), "flash get HW_LIGHT_SN", "=" + deviceData.LightModuleSN, "=" + deviceData.LightModuleSN);
            writeResult = TelnetSendAndRecv(tel, string.Format("flash set HW_LIGHT_SN {0}", deviceData.LightModuleSN), "=" + deviceData.LightModuleSN);
            if (writeResult == false) { SetResultOne("写光模块序列号失败", false); return false; }
            else { SetResultOne("写光模块序列号成功", true); }

            //光模块型号
            string lightModel = string.IsNullOrEmpty(deviceData.LightModuleSN) ? DateTime.Now.ToString("yyyyMM00") : deviceData.LightModuleSN.Substring(0, 8);
            //writeResult = WriteAndReadMsg(tel, string.Format("flash set HW_LIGHT_MODEL {0}", deviceData.LightModule), "flash get HW_LIGHT_MODEL", "=" + deviceData.LightModule, "=" + deviceData.LightModule);
            writeResult = TelnetSendAndRecv(tel, string.Format("flash set HW_LIGHT_MODEL {0}", lightModel), "=" + lightModel);
            if (writeResult == false) { SetResultOne("写光模块型号失败", false); return false; }
            else { SetResultOne("写光模块型号成功", true); }

            //GPON_SN，只有GPON才写SN号码
            if (deviceData.PONType == "STIA")
            {
                //writeResult = WriteAndReadMsg(tel, string.Format("flash set GPON_SN {0}", deviceData.XPON_SN), "flash get GPON_SN", "=" + deviceData.XPON_SN, "=" + deviceData.XPON_SN);
                writeResult = TelnetSendAndRecv(tel, string.Format("flash set GPON_SN {0}", deviceData.XPON_SN), "=" + deviceData.XPON_SN);
                if (writeResult == false) { SetResultOne("写GPON_SN失败", false); return false; }
                else { SetResultOne("写GPON_SN成功", true); }
            }

            //厂商名称
            //string companyName = "youhua";
            //writeResult = WriteAndReadMsg(tel, string.Format("flash set HW_CWMP_MANUFACTURER {0}", companyName), "flash get HW_CWMP_MANUFACTURER", "=" + companyName, "=" + companyName);
            writeResult = TelnetSendAndRecv(tel, string.Format("flash set HW_CWMP_MANUFACTURER {0}", deviceType.Manufacturer), "=" + deviceType.Manufacturer);
            if (writeResult == false) { SetResultOne("写厂商名称失败", false); return false; }
            else { SetResultOne("写厂商名称成功", true); }

            //版本校验码key
            //writeResult = WriteAndReadMsg(tel, string.Format("flash set HW_CIPHER {0}", deviceData.HW_CIPHER), "flash get HW_CIPHER", "=" + deviceData.HW_CIPHER, "=" + deviceData.HW_CIPHER);
            writeResult = TelnetSendAndRecv(tel, string.Format("flash set HW_CIPHER {0}", deviceData.HW_CIPHER), "=" + deviceData.HW_CIPHER);
            if (writeResult == false) { SetResultOne("写版本校验码KEY失败", false); return false; }
            else { SetResultOne("写版本校验码KEY成功", true); }

            //软件版本校验码copyright
            //writeResult = WriteAndReadMsg(tel, string.Format("flash set HW_COPYRIGHT {0}", deviceType.HWCopyright), "flash get HW_COPYRIGHT", "=" + deviceType.HWCopyright, "=" + deviceType.HWCopyright);
            writeResult = TelnetSendAndRecv(tel, string.Format("flash set HW_COPYRIGHT {0}", deviceType.HWCopyright), "=" + deviceType.HWCopyright);
            if (writeResult == false) { SetResultOne("写软件版本校验码copyright失败", false); return false; }
            else { SetResultOne("写软件版本校验码copyright成功", true); }

            //写省份信息
            //writeResult = WriteAndReadMsg(tel, string.Format("flash set HW_PROVINCE_NAME {0}", deviceData.HW_PROVINCE_NAME), "flash get HW_PROVINCE_NAME", "=" + deviceData.HW_PROVINCE_NAME, "=" + deviceData.HW_PROVINCE_NAME);
            writeResult = TelnetSendAndRecv(tel, string.Format("flash set HW_PROVINCE_NAME {0}", deviceData.HW_PROVINCE_NAME), "=" + deviceData.HW_PROVINCE_NAME);
            if (writeResult == false) { SetResultOne("写省份信息失败", false); return false; }
            else { SetResultOne("写省份信息成功", true); }

            //写ITV_MAC和STBID
            if (string.IsNullOrEmpty(deviceData.ITV_MAC) == false)
            {
                writeResult = TelnetSendAndRecv(tel, string.Format("flash set SMART_IPTV_BURN_MAC {0}", deviceData.ITV_MAC),  $"{deviceData.ITV_MAC}\r\n#");
                if (writeResult == false) { SetResultOne("写ITV MAC失败", false); return false; }
                else { SetResultOne("写ITV MAC成功", true); }

                writeResult = TelnetSendAndRecv(tel, string.Format("flash set SMART_IPTV_BURN_STBID {0}", deviceData.STBID),  $"{deviceData.STBID}\r\n#");
                if (writeResult == false) { SetResultOne("写ITV STBID失败", false); return false; }
                else { SetResultOne("写ITV STBID成功", true); }
            }

            //关闭常发光指令
            //writeResult = WriteAndReadMsg(tel, "flash set USER_FACTORY_BEFORE_RUN 0", null, "USER_FACTORY_BEFORE_RUN=", null);
            writeResult = TelnetSendAndRecv(tel, "flash set USER_FACTORY_BEFORE_RUN 0", "USER_FACTORY_BEFORE_RUN=");
            if (writeResult == false) { SetResultOne("关闭常发光失败", false); return false; }
            else { SetResultOne("关闭常发光成功", true); }


            writeResult = TelnetSendAndRecv(tel, "rm opt/upt/apps/apps/etc/config/cloudclient", "#");
            if (writeResult == false) { SetResultOne("执行删除指令失败", false); return false; }
            else { SetResultOne("执行删除指成功", true); }

            writeResult = TelnetSendAndRecv(tel, " cat opt/upt/apps/apps/etc/config/cloudclient", "No such file or directory");
            if (writeResult == false) { SetResultOne("验证失败", false); return false; }
            else { SetResultOne("验证成功", true); }

            return true;
        }

        /// <summary>
        /// 写R方案的信息
        /// </summary>
        /// <param name="deviceData"></param>
        /// <returns></returns>
        private bool CheckDeviceDataR(Device_Data deviceData, Device_Type deviceType, YcdTelnetSecond tel)
        {
            //检查key copyright province信息是否是空值
            if (string.IsNullOrEmpty(deviceData.HW_CIPHER) || string.IsNullOrEmpty(deviceData.HW_PROVINCE_NAME) || string.IsNullOrEmpty(deviceType.HWCopyright))
            {
                SetResultOne("KEY COPYRIGHT PROVINCE三个数据为空", false);
                return false;
            }

            //MAC烧录
            //var readResult = WriteAndReadMsg(tel, string.Format("flash set ELAN_MAC_ADDR {0}", deviceData.MACAddr), "flash get ELAN_MAC_ADDR", deviceData.MACAddr, deviceData.MACAddr);
            var readResult = TelnetSendAndRecv(tel, "flash get ELAN_MAC_ADDR", deviceData.MACAddr);
            if (readResult == false) { SetResultOne("检查MAC地址失败", false); return false; }
            else { SetResultOne("检查MAC地址成功", true); }

            //设备序列号
            //readResult = WriteAndReadMsg(tel, string.Format("flash set HW_SERIAL_NO {0}", deviceData.OUI2), "flash get HW_SERIAL_NO", deviceData.OUI2, deviceData.OUI2);
            readResult = TelnetSendAndRecv(tel, "flash get HW_SERIAL_NO", deviceData.OUI2);
            if (readResult == false) { SetResultOne("检查设备序列号失败", false); return false; }
            else { SetResultOne("检查设备序列号成功", true); }


            //设备型号
            //ADD_18.3.20，兼容新的类型
            string type = deviceData.DeviceType.Replace(" ", "");
            if (type.Contains("_"))
            {
                type = type.Substring(0, type.IndexOf("_"));
            }

            //readResult = WriteAndReadMsg(tel, string.Format("flash set HW_CWMP_PRODUCTCLASS {0}", type), "flash get HW_CWMP_PRODUCTCLASS", type, type);
            readResult = TelnetSendAndRecv(tel, "flash get HW_CWMP_PRODUCTCLASS", type);
            if (readResult == false) { SetResultOne("检查设备型号失败", false); return false; }
            else { SetResultOne("检查设备型号成功", true); }

            //校验软件版本信息
            //readResult = WriteAndReadMsg(tel, null, "cat /etc/swver", null, deviceType.SWVersion);
            readResult = TelnetSendAndRecv(tel, "cat /etc/swver", deviceType.SWVersion);
            if (readResult == false) { SetResultOne("检查软件版本失败", false); return false; }
            else { SetResultOne("检查软件版本成功", true); }

            //校验软件编译时间
            //readResult = WriteAndReadMsg(tel, null, "cat /etc/swver", null, deviceType.BuildTime);
            readResult = TelnetSendAndRecv(tel, "cat /etc/swver", deviceType.BuildTime);
            if (readResult == false) { SetResultOne("校验编译时间失败", false); return false; }
            else { SetResultOne("校验编译时间成功", true); }

            //硬件版本
            //readResult = WriteAndReadMsg(tel, string.Format("flash set HW_HWVER {0}", deviceType.HWVersion), "flash get HW_HWVER", deviceType.HWVersion, deviceType.HWVersion);
            readResult = TelnetSendAndRecv(tel, "flash get HW_HWVER", deviceType.HWVersion);
            if (readResult == false) { SetResultOne("检查设备硬件版本失败", false); return false; }
            else { SetResultOne("检查设备硬件版本成功", true); }

            //普通用户密码
            //readResult = WriteAndReadMsg(tel, string.Format("flash set DEFAULT_USER_PASSWORD {0}", deviceData.WedPassword), "flash get DEFAULT_USER_PASSWORD", deviceData.WedPassword, deviceData.WedPassword);
            readResult = TelnetSendAndRecv(tel, "flash get DEFAULT_USER_PASSWORD", deviceData.WedPassword);
            if (readResult == false) { SetResultOne("检查普通用户密码失败", false); return false; }
            else { SetResultOne("检查普通用户密码成功", true); }

            //无线名称
            //readResult = WriteAndReadMsg(tel, string.Format("flash set DEFAULT_WLAN_SSID {0}", deviceData.WIFI_SSID), "flash get DEFAULT_WLAN_SSID", deviceData.WIFI_SSID, deviceData.WIFI_SSID);
            readResult = TelnetSendAndRecv(tel, "flash get DEFAULT_WLAN_SSID", deviceData.WIFI_SSID);
            if (readResult == false) { SetResultOne("检查WIFI名称失败", false); return false; }
            else { SetResultOne("检查WIFI名称成功", true); }

            //无线密钥
            //readResult = WriteAndReadMsg(tel, string.Format("flash set DEFAULT_WLAN_WPAKEY {0}", deviceData.WIFI_Password), "flash get DEFAULT_WLAN_WPAKEY", deviceData.WIFI_Password, deviceData.WIFI_Password);
            readResult = TelnetSendAndRecv(tel, "flash get DEFAULT_WLAN_WPAKEY", deviceData.WIFI_Password);
            if (readResult == false) { SetResultOne("检查WIFI密码失败", false); return false; }
            else { SetResultOne("检查WIFI密码成功", true); }

            //ITV名称
            //readResult = WriteAndReadMsg(tel, string.Format("flash set HW_SSID2ND {0}", deviceData.ITV_SSID), "flash get HW_SSID2ND", deviceData.ITV_SSID, deviceData.ITV_SSID);
            readResult = TelnetSendAndRecv(tel, "flash get HW_SSID2ND", deviceData.ITV_SSID);
            if (readResult == false) { SetResultOne("检查ITV SSID名称失败", false); return false; }
            else { SetResultOne("检查ITV SSID成功", true); }

            //ITV密钥
            //readResult = WriteAndReadMsg(tel, string.Format("flash set HW_WPAKEY2ND {0}", deviceData.ITV_Password), "flash get HW_WPAKEY2ND", deviceData.ITV_Password, deviceData.ITV_Password);
            readResult = TelnetSendAndRecv(tel, "flash get HW_WPAKEY2ND", deviceData.ITV_Password);
            if (readResult == false) { SetResultOne("检查ITV 密码失败", false); return false; }
            else { SetResultOne("检查ITV 密码成功", true); }

            //光模块型号
            //readResult = WriteAndReadMsg(tel, string.Format("flash set HW_LIGHT_MODEL {0}", deviceData.LightModule), "flash get HW_LIGHT_MODEL", deviceData.LightModule, deviceData.LightModule);
            readResult = TelnetSendAndRecv(tel, "flash get HW_LIGHT_MODEL", deviceData.ProductCode);
            if (readResult == false) { SetResultOne("检查光模块型号失败", false); return false; }
            else { SetResultOne("检查光模块型号成功", true); }

            //光模块序列号
            //readResult = WriteAndReadMsg(tel, string.Format("flash set HW_LIGHT_SN {0}", deviceData.LightModuleSN), "flash get HW_LIGHT_SN", deviceData.LightModuleSN, deviceData.LightModuleSN);
            readResult = TelnetSendAndRecv(tel, "flash get HW_LIGHT_SN", deviceData.LightModuleSN);
            if (readResult == false) { SetResultOne("检查光模块序列号失败", false); return false; }
            else { SetResultOne("检查光模块序列号成功", true); }

            //GPON_SN，只有GPON才检查SN号码
            if (deviceType.XPONMode == "GPON")
            {
                //readResult = WriteAndReadMsg(
                //    tel,
                //    "flash get GPON_SN",
                //    string.Format("flash set GPON_SN {0}", deviceData.XPON_SN),
                //    "=" + deviceData.XPON_SN,
                //    "=" + deviceData.XPON_SN);//2018年3月20日修改，兼容跑流算法
                readResult = TelnetSendAndRecv(tel, string.Format("flash set GPON_SN {0}", deviceData.XPON_SN), "=" + deviceData.XPON_SN);//兼容跑流
                if (readResult == false) { SetResultOne("写GPON_SN失败", false); return false; }
                else { SetResultOne("写GPON_SN成功", true); }
            }

            //XPON型号
            string ponMode = null;
            if (deviceType.XPONMode == "GPON")
            {
                ponMode = "1";
            }
            else
            {
                ponMode = "2";
            }

            //readResult = WriteAndReadMsg(tel, string.Format("flash set PON_MODE {0}", ponMode), "flash get PON_MODE", ponMode, ponMode);
            readResult = TelnetSendAndRecv(tel, "flash get PON_MODE", ponMode);
            if (readResult == false) { SetResultOne("检查PON的型号失败", false); return false; }
            else { SetResultOne("检查PON的型号成功", true); }

            //厂商名称
            string companyName = "youhua";
            //readResult = WriteAndReadMsg(tel, string.Format("flash set HW_CWMP_MANUFACTURER {0}", companyName), "flash get HW_CWMP_MANUFACTURER", companyName, companyName);
            readResult = TelnetSendAndRecv(tel, "flash get HW_CWMP_MANUFACTURER", companyName);
            if (readResult == false) { SetResultOne("检查厂商名称失败", false); return false; }
            else { SetResultOne("检查厂商名称成功", true); }

            //版本校验码key
            //readResult = WriteAndReadMsg(tel, string.Format("flash set HW_CIPHER {0}", deviceData.HW_CIPHER), "flash get HW_CIPHER", deviceData.HW_CIPHER, deviceData.HW_CIPHER);
            readResult = TelnetSendAndRecv(tel, "flash get HW_CIPHER", deviceData.HW_CIPHER);
            if (readResult == false) { SetResultOne("检查版本校验码KEY失败", false); return false; }
            else { SetResultOne("检查版本校验码KEY成功", true); }

            //软件版本校验码copyright
            //readResult = WriteAndReadMsg(tel, string.Format("flash set HW_COPYRIGHT {0}", deviceType.HWCopyright), "flash get HW_COPYRIGHT", deviceType.HWCopyright, deviceType.HWCopyright);
            readResult = TelnetSendAndRecv(tel, "flash get HW_COPYRIGHT", deviceType.HWCopyright);
            if (readResult == false) { SetResultOne("检查软件版本校验码copyright失败", false); return false; }
            else { SetResultOne("检查软件版本校验码copyright成功", true); }

            //检查省份信息
            //readResult = WriteAndReadMsg(tel, string.Format("flash set HW_PROVINCE_NAME {0}", deviceData.HW_PROVINCE_NAME), "flash get HW_PROVINCE_NAME", deviceData.HW_PROVINCE_NAME, deviceData.HW_PROVINCE_NAME);
            readResult = TelnetSendAndRecv(tel, "flash get HW_PROVINCE_NAME", deviceData.HW_PROVINCE_NAME);
            if (readResult == false) { SetResultOne("检查省份信息失败", false); return false; }
            else { SetResultOne("检查省份信息成功", true); }

            //检查长发光是否关闭了
            //关闭常发光指令
            //readResult = WriteAndReadMsg(tel, null, "flash get USER_FACTORY_BEFORE_RUN", null, "USER_FACTORY_BEFORE_RUN=0");
            readResult = TelnetSendAndRecv(tel, "flash get USER_FACTORY_BEFORE_RUN", "USER_FACTORY_BEFORE_RUN=0");
            if (readResult == false) { SetResultOne("检查长发光，未关闭", false); return false; }
            else { SetResultOne("检查长发光，已关闭", true); }

            return true;
        }
        /// <summary>
        /// 检查MTK方案的信息
        /// </summary>
        /// <param name="deviceData"></param>
        /// <returns></returns>
        private bool CheckDeviceDataMtk(Device_Data deviceData, Device_Type deviceType, YcdTelnetSecond tel)
        {
            ////清除区域指令
            //var writeResult = WriteAndReadMsg(tel, "prolinecmd clear 1", null, "write", null);
            //if (writeResult == false) { SetResultOne("清除区域指令失败", false); return false; }
            //else { SetResultOne("清除区域指令成功", true); }


            //检查MAC
            var writeResult = WriteAndReadMsg(tel, string.Format("sys mac {0} -n", deviceData.MACAddr), null, "addr", null);
            if (writeResult == false) { SetResultOne("检查MAC地址失败", false); return false; }
            else { SetResultOne("检查MAC地址成功", true); }

            //检查productclass
            writeResult = WriteAndReadMsg(tel
                , string.Format("prolinecmd productclass set {0}", deviceData.DeviceType.Replace(" ", ""))
                , "prolinecmd productclass display"
                , "readflash"
                , deviceData.DeviceType.Replace(" ", ""));

            if (writeResult == false) { SetResultOne("检查Productclass失败", false); return false; }
            else
            {
                SetResultOne("检查Productclass成功", true);
            }
            //检查oui1
            writeResult = WriteAndReadMsg(tel
                , string.Format("prolinecmd manufacturerOUI set  {0}", deviceData.OUI1)
                , "prolinecmd manufacturerOUI display"
                , "readflash"
                , deviceData.OUI1);

            if (writeResult == false) { SetResultOne("检查OUI1失败", false); return false; }
            else { SetResultOne("检查OUI1成功", true); }
            //检查oui2
            writeResult = WriteAndReadMsg(tel
                , string.Format("prolinecmd serialnum set  {0}", deviceData.OUI2)
                , "prolinecmd serialnum display"
                , "readflash"
                , deviceData.OUI2);

            if (writeResult == false) { SetResultOne("检查OUI2失败", false); return false; }
            else { SetResultOne("检查OUI2成功", true); }
            //检查硬件版本信息
            writeResult = WriteAndReadMsg(tel
                , string.Format("prolinecmd hwver set  {0}", deviceType.HWVersion)
                , "prolinecmd hwver display"
                , "readflash"
                , deviceType.HWVersion);

            if (writeResult == false) { SetResultOne("检查硬件版本失败", false); return false; }
            else { SetResultOne("检查硬件版本成功", true); }
            //校验软件版本信息
            writeResult = WriteAndReadMsg(tel
                , null
                , "cat /etc/swver"
                , null
                , deviceType.SWVersion);

            if (writeResult == false) { SetResultOne("检查软件版本失败", false); return false; }
            else { SetResultOne("检查软件版本成功", true); }
            //校验软件编译时间
            writeResult = WriteAndReadMsg(tel
                , null
                , "cat /etc/swver"
                , null
                , deviceType.BuildTime);

            if (writeResult == false) { SetResultOne("校验编译时间失败", false); return false; }
            else { SetResultOne("校验编译时间成功", true); }
            //检查光模块SN
            writeResult = WriteAndReadMsg(tel
                , string.Format("prolinecmd lightmodulesn set {0}", deviceData.LightModuleSN)
                , "prolinecmd lightmodulesn display"
                , "readflash"
                , deviceData.LightModuleSN);

            if (writeResult == false) { SetResultOne("检查光模块SN失败", false); return false; }
            else { SetResultOne("检查光模块SN成功", true); }
            //检查光模块型号
            writeResult = WriteAndReadMsg(tel
                , string.Format("prolinecmd lightmodule set {0}", deviceData.ProductCode)
                , "prolinecmd lightmodule display"
                , "readflash"
                , deviceData.ProductCode);

            if (writeResult == false) { SetResultOne("检查光模块型号失败", false); return false; }
            else { SetResultOne("检查光模块型号成功", true); }
            //检查WIFI SSID
            writeResult = WriteAndReadMsg(tel
                , string.Format("prolinecmd ssid  set {0}", deviceData.WIFI_SSID)
                , "prolinecmd ssid  display"
                , "readflash"
                , deviceData.WIFI_SSID);

            if (writeResult == false) { SetResultOne("检查wifi ssid失败", false); return false; }
            else { SetResultOne("检查WiFi ssid成功", true); }
            //检查WIFI密码
            writeResult = WriteAndReadMsg(tel
                , string.Format("prolinecmd wpakey  set {0}", deviceData.WIFI_Password)
                , "prolinecmd wpakey  display"
                , "readflash"
                , deviceData.WIFI_Password);

            if (writeResult == false) { SetResultOne("检查WiFi密码失败", false); return false; }
            else { SetResultOne("检查wifi密码成功", true); }
            //检查ITVSSID
            writeResult = WriteAndReadMsg(tel
                , string.Format("prolinecmd ssid2nd  set {0}", deviceData.ITV_SSID)
                , "prolinecmd ssid2nd   display"
                , "readflash"
                , deviceData.ITV_SSID);

            if (writeResult == false) { SetResultOne("检查ITV SSID失败", false); return false; }
            else { SetResultOne("检查ITV SSID 成功", true); }
            //检查ITV密码
            writeResult = WriteAndReadMsg(tel
                , string.Format("prolinecmd wpakey2nd  set {0}", deviceData.ITV_Password)
                , "prolinecmd wpakey2nd   display"
                , "readflash"
                , deviceData.ITV_Password);

            if (writeResult == false) { SetResultOne("检查ITV 密码失败", false); return false; }
            else { SetResultOne("检查ITV密码成功", true); }
            //检查web用户名
            writeResult = WriteAndReadMsg(tel
                , string.Format("prolinecmd webAccount  set {0}", deviceData.WedUser)
                , "prolinecmd webAccount   display"
                , "readflash"
                , deviceData.WedUser);

            if (writeResult == false) { SetResultOne("检查web用户名称失败", false); return false; }
            else { SetResultOne("检查web用户名称成功", true); }
            //检查web密码
            writeResult = WriteAndReadMsg(tel
                , string.Format("prolinecmd webpwd set {0}", deviceData.WedPassword)
                , "prolinecmd webpwd  display"
                , "readflash"
                , deviceData.WedPassword);

            if (writeResult == false) { SetResultOne("检查web密码失败", false); return false; }
            else { SetResultOne("检查web密码成功", true); }
            //检查XPON modem
            writeResult = WriteAndReadMsg(tel
                , string.Format("prolinecmd xponmode set {0}", deviceType.XPONMode)
                , "prolinecmd xponmode display"
                , "readflash"
                , deviceType.XPONMode);

            if (writeResult == false) { SetResultOne("检查XPON MODEM失败", false); return false; }
            else { SetResultOne("检查XPON MODEM成功", true); }
            //检查XPON SN
            writeResult = WriteAndReadMsg(tel
                , string.Format("prolinecmd xponsn set {0}", deviceData.XPON_SN)
                , "prolinecmd xponsn display"
                , "readflash"
                , deviceData.XPON_SN);

            if (writeResult == false) { SetResultOne("检查XPON_SN失败", false); return false; }
            else { SetResultOne("检查XPON_SN成功", true); }

            //检查长发光
            return true;
        }

        /// <summary>
        /// TELNET命令
        /// </summary>
        /// <param name="tel"></param>
        /// <param name="cmdStr"></param>
        /// <param name="keyWord"></param>
        /// <returns></returns>
        private bool TelnetSendAndRecv(YcdTelnetSecond tel, string cmdStr, string keyWord)
        {
            if (tel == null || tel.Connected == false || string.IsNullOrEmpty(cmdStr) || string.IsNullOrEmpty(keyWord)) return false;

            //发送telnet指令_语音测试
            //tel.Send(cmdStr);


            //bool ret = tel.GetReturnMsg(keyWord, out msg);

            bool ret = tel.SendAndRecv(cmdStr, keyWord, out string msg, 5000);

            AppendRichTextBox(msg);

            return ret;
        }

        //检查信息和回显信息，MTK和R通用
        private bool WriteAndReadMsg(YcdTelnetSecond tel, string writeCmd, string readCmd, string keyWordWrite, string keyWordRead)
        {
            if (string.IsNullOrEmpty(writeCmd) && string.IsNullOrEmpty(readCmd)) return false;

            //修改writeCmd为空，不写信息
            writeCmd = null;

            //写信息
            if (string.IsNullOrEmpty(writeCmd) == false)
            {
                //tel.Send(writeCmd);

                string value;
                //bool hasKey = tel.GetReturnMsg(keyWordWrite.Trim(), out value);

                bool hasKey = tel.SendAndRecv(writeCmd, keyWordWrite, out value);

                //写LOG
                //WriteLog(value);
                AppendRichTextBox(value);

                if (hasKey == false) return false;
            }

            //读取信息
            if (string.IsNullOrEmpty(readCmd) == false)
            {
                //tel.Send(readCmd);

                string value;
                //bool hasKey = tel.GetReturnMsg(keyWordRead.Trim(), out value);

                bool hasKey = tel.SendAndRecv(readCmd, keyWordRead, out value);


                //写log
                //WriteLog(value);
                AppendRichTextBox(value);

                if (hasKey == false) return false;
            }

            return true;
        }

        /// <summary>
        /// 连接并登陆光猫，返回类，若为空则链接失败
        /// </summary>
        /// <returns></returns>
        private YcdTelnetSecond TelnetModem()
        {
            //使用新的类YcdTelnetSecond
            if (_portOffset >= 500) _portOffset = 0;
            _portOffset++;

            YcdTelnetSecond telnet = new YcdTelnetSecond(_modemIp, _localIp, _localPort + _portOffset);
            if (telnet.Connect() == false)
            {
                return null;
            }

            string msg;

            bool telRet = false;

            if (telnet.SendAndRecv(null, "login", out msg))
            {
                AppendRichTextBox("输入用户名称……");
                if (telnet.SendAndRecv(_modemUser, "password", out msg))
                {
                    AppendRichTextBox("输入用户密码……");
                    if (telnet.SendAndRecv(_modemPwd, "#", out msg))
                    {
                        AppendRichTextBox("登录成功");
                        telRet = true;
                    }
                }
            }

            if (telRet == false) { AppendRichTextBox("登录失败"); return null; }

            AppendRichTextBox(msg);

            return telnet;
        }

        //private void ResetModem(YcdTelnetSecond tel, string deviceType)
        //{
        //    Thread.Sleep(1000);

        //    string msg;

        //    if (_modemType == ModemType.DX_9603)
        //    {
        //        tel.SendAndRecv("flash default cs", "reboot", out msg, 10000);
        //    }
        //    else
        //    {
        //        tel.SendAndRecv("mp_default", "reboot", out msg, 10000);
        //    }

        //    AppendRichTextBox(msg);


        //    tel.Send("reboot -f");

        //    AppendRichTextBox("reboot -f\r\n重置光猫开始……");
        //}

        /// <summary>
        /// 获取产品类型信息
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        private Device_Type GetDeviceType(string type, string province)
        {
            var device = (from t in _listType
                          where t.DeviceType == type && t.PROVINCE == province
                          select t).FirstOrDefault();

            return device;
        }



        //定位到mac输入位置，重置信息
        private void MacFocus()
        {
            if (this.textBoxMacAddr.InvokeRequired)
            {
                Action d = new Action(MacFocus);
                Invoke(d);
            }
            else
            {
                //清除list中的mac信息
                lock (PublicData.LOCKOBJUI)
                    this.textBoxMacAddr.Clear();
                //this.textBoxXponSn.Clear();
                //this.textBoxMacAddr.Focus();
                //this.labelTestResult.ForeColor = Color.Black;
                //this.labelTestResult.Text = "";
            }
        }

        //设置textBox是否能够使用
        private void SetTextBoxReadOnly(bool enable = false)
        {
            if (this.textBoxMacAddr.InvokeRequired)
            {
                Action<bool> d = new Action<bool>(SetTextBoxReadOnly);
                Invoke(d, enable);
            }
            else
            {
                lock (PublicData.LOCKOBJUI)
                    this.textBoxMacAddr.ReadOnly = enable;
                //this.textBoxXponSn.Enabled = enable;
                //this.richTextBoxMsg.Enabled = enable;
            }
        }

        //将信息检查信息窗口
        private void AppendRichTextBox(string value)
        {
            if (this.richTextBoxMsg.InvokeRequired)
            {
                Action<string> d = new Action<string>(AppendRichTextBox);
                Invoke(d, new object[] { value });
            }
            else
            {
                if (string.IsNullOrEmpty(value)) return;
                //if (this.richTextBoxMsg.TextLength >= 5000)
                //    lock (PublicData.LOCKOBJUI)
                //        this.richTextBoxMsg.Clear();

                value = value.Replace("\0", "");

                WriteLog(value);

                lock (PublicData.LOCKOBJUI)
                    this.richTextBoxMsg.AppendText(value + "\r\n");
            }
        }

        //设置结果
        //private void SetTestState(bool result, string msg = null)
        //{
        //    if (labelTestResult.InvokeRequired)
        //    {
        //        Action<bool, string> d = new Action<bool, string>(SetTestState);
        //        Invoke(d, result, msg);
        //    }
        //    else
        //    {
        //        if (result && msg == null)
        //        {
        //            this.labelTestResult.ForeColor = Color.Green;
        //            this.labelTestResult.Text = "PASS";
        //        }
        //        else if (result == false && msg == null)
        //        {
        //            this.labelTestResult.ForeColor = Color.Red;
        //            this.labelTestResult.Text = "FAIL";
        //        }
        //        else if (msg != null && result == false)
        //        {
        //            this.labelTestResult.ForeColor = Color.Black;
        //            this.labelTestResult.Text = msg;
        //        }
        //        else if (msg != null && result)
        //        {
        //            this.labelTestResult.ForeColor = Color.BlueViolet;
        //            this.labelTestResult.Text = msg;
        //        }
        //    }
        //}

        private void SetControlText(Control con, string text, Color color)
        {
            if (this.InvokeRequired)
            {
                Action<Control, string, Color> d = new Action<Control, string, Color>(SetControlText);
                Invoke(d, con, text, color);
            }
            else
            {
                lock (PublicData.LOCKOBJUI)
                {
                    con.ForeColor = color;
                    if (string.IsNullOrEmpty(text) == false)
                        con.Text = text;
                }
            }
        }

        //给外部使用的获取焦点方法
        public void SetFocusMac()
        {
            if (this.textBoxMacAddr.InvokeRequired)
            {
                Action d = new Action(MacFocus);
                Invoke(d);
            }
            else
            {
                lock (PublicData.LOCKOBJUI)
                    this.textBoxMacAddr.Focus();
            }
        }

        //private object lockLog = new object();//锁定LOG写
        ///// <summary>
        ///// 写log信息
        ///// </summary>
        ///// <param name="msg"></param>
        //private void WriteLog(string msg)
        //{
        //    lock (lockLog)
        //        _log = string.Format("{0}{1}\r\n", _log, msg);
        //}

        /// <summary>
        /// 一个信息检查结束时操作
        /// </summary>
        private void FinallyDone(string macAddr = null, bool result = false)
        {
            if (macAddr != null)
                PublicData.ListAddress.Remove(macAddr);
            //SetTestState(result);//展示最后结果
            if (result)
            {
                SetControlText(this.labelTestResult, "PASS", Color.Green);
            }
            else
            {
                SetControlText(this.labelTestResult, "FAIL", Color.Red);
            }


            //添加测试数量
            //SetTestNum(++_testNum);
            if (_autoReadMac != "1")
            {
                SetTextBoxReadOnly(false);//设置textbox可用
                MacFocus();
            }//清空mac/sn

            if (_autoReadMac == "1")
            {
                GetMacArp();
            }

            OnFinished?.BeginInvoke(_myFormNum, null, null);//发送完成的消息

            System.Threading.Thread.Sleep(45000);

            //SetTestState(false, "WAIT");
            SetControlText(this.labelTestResult, "WAIT", Color.Black);
        }

        private void ClearText(Control con)
        {
            if (this.InvokeRequired)
            {
                Action<Control> d = new Action<Control>(ClearText);
                Invoke(d, con);
            }
            else
            {
                lock (PublicData.LOCKOBJUI)
                    con.Text = null;
            }
        }

        private void richTextBoxMsg_TextChanged(object sender, EventArgs e)
        {
            lock (PublicData.LOCKOBJUI)
            {
                richTextBoxMsg.SelectionStart = richTextBoxMsg.Text.Length;
                richTextBoxMsg.ScrollToCaret();
            }
        }

        //写单项结果
        private void SetResultOne(string msg, bool result)
        {
            if (this.labelResultOne.InvokeRequired)
            {
                Action<string, bool> d = new Action<string, bool>(SetResultOne);
                Invoke(d, msg, result);
            }
            else
            {
                lock (PublicData.LOCKOBJUI)
                {
                    this.labelResultOne.Text = msg;
                    if (result) this.labelResultOne.ForeColor = Color.Green;
                    else this.labelResultOne.ForeColor = Color.Red;
                }
                WriteLog(msg);
            }
        }

        private string GetListLog()
        {
            //StringBuilder allLog = new StringBuilder();
            //for (int i = 0; i < _listLog.Count; i++)
            //{
            //    allLog.Append(_listLog[i] + "\r\n");
            //}
            //return allLog.ToString();
            //if (_listLog.Length > 65535) _listLog = _listLog.Substring(0, 65535);
            //AppendRichTextBox("日志长度为：" + _listLog.Length);

            return _listLog;
        }

        /// <summary>
        /// 写log信息
        /// </summary>
        /// <param name="msg"></param>
        private void WriteLog(string msg)
        {
            lock (lockLog)
                _listLog = string.Format("{0}{1}\r\n", _listLog, msg);
        }

        private void textBoxMacAddr_Enter(object sender, EventArgs e)
        {
            lock (PublicData.LOCKOBJUI)
                this.BackColor = Color.LightBlue;
        }

        private void textBoxMacAddr_Leave(object sender, EventArgs e)
        {
            lock (PublicData.LOCKOBJUI)
                this.BackColor = Color.FromArgb(255, 240, 240, 240);
        }


        //Color backcolor;
        //private void textBoxMacAddr_Enter(object sender, EventArgs e)
        //{
        //    backcolor = this.textBoxMacAddr.BackColor;
        //    this.textBoxMacAddr.BackColor = Color.LightBlue;
        //}

        //private void textBoxMacAddr_Leave(object sender, EventArgs e)
        //{
        //    this.textBoxMacAddr.BackColor = backcolor;
        //}
    }
}
